<!-- 评估问卷 -->
<script setup lang="ts">
import { fetchAssessmentListAPI } from '@/apis/fetchAssessmentList'
import { submitAssessmentAPI } from '@/apis/submitAssessment'
import router from '@/router'
import { useUserInfoStore } from '@/store/userInfo'

const userInfoStore = useUserInfoStore()

const loading = ref(false)

// 班级 id
const classId = ref('')
// 试题列表
const questionList = ref<Question[]>([])

// 当前翻到第几题了
const currentIndex = ref(0)
// 当前的题
const currentQuestion = computed(() => {
  return questionList.value[currentIndex.value]
})

// 表单数据
const formData = ref<{ id: string, answer: string | string[] }[]>([])
// 当前题目的表单数据
const currentFormData = computed(() => {
  return formData.value[currentIndex.value]
})

// 是否显示提交成功的 Dialog
const isShowSuccessDialog = ref(false)

// 页面加载时获取班级 id 和试题数据
onLoad(async (options) => {
  if (options && options.class_id) {
    classId.value = options.class_id
    try {
      loading.value = true
      const res = await fetchAssessmentListAPI(options.class_id, userInfoStore.userInfo!.token!)
      if (res.data?.code === 1) {
        questionList.value = res.data.data

        formData.value = questionList.value.map((q) => {
          return {
            id: q.id.toString(),
            answer: q.kind === 'FILL' ? '' as string : [] as string[],
          }
        })
        loading.value = false
      }
      else {
        uni.showToast({ title: res.data?.msg, icon: 'none' })
        loading.value = false
      }
    }
    catch (err) {
      uni.showToast({ title: JSON.stringify(err), icon: 'none' })
    }
  }
  else {
    uni.showToast({ title: '获取数据失败：没有班级id', icon: 'none' })
  }
})

// 根据传入的 kind，获取对应的试题类型名称
function questionKindName(kind: 'FILL' | 'JUDGE' | 'SINGLE') {
  if (kind === 'JUDGE')
    return '单选题'
  else if (kind === 'SINGLE')
    return '多选题'
  else if (kind === 'FILL')
    return '简答题'
}

/**
 * @description 输入框内容更新时触发
 *
 * @param e - TextareaInputEvent
 */
function handleInput(e: any) {
  currentFormData.value.answer = e.detail.value
}

/**
 * @description 点击选项时触发
 *
 * @param optionKey - 选项 Key，如 A，B，C 等
 */
function handleTapOption(optionKey: string) {
  if (currentQuestion.value.kind === 'JUDGE') {
    currentFormData.value.answer = [optionKey]
  }
  else if (currentQuestion.value.kind === 'SINGLE') {
    if (currentFormData.value.answer.includes(optionKey)) {
      currentFormData.value.answer = (currentFormData.value.answer as string[])
        .filter(item => item !== optionKey)
    }
    else {
      (currentFormData.value.answer as string[]).push(optionKey)
    }
  }
}

function handleTapNextButton() {
  if (formData.value[currentIndex.value].answer.length === 0) {
    uni.showToast({ title: '请先作答当前题目', icon: 'none' })
    return
  }

  currentIndex.value += 1
}

/**
 * @description 提交表单时触发
 */
async function handleSubmit() {
  for (const item of formData.value) {
    if (!item.answer) {
      uni.showToast({ title: '请填选所有题目后再提交', icon: 'none' })
      return
    }
  }

  const transformedFormData = formData.value.map((item) => {
    if (Array.isArray(item.answer)) {
      return {
        id: item.id,
        answer: item.answer.join(','),
      }
    }
    else {
      return item as { id: string, answer: string }
    }
  })

  try {
    const res = await submitAssessmentAPI({
      classes_id: classId.value,
      user_answers: JSON.stringify(transformedFormData),
    }, userInfoStore.userInfo!.token!)

    if (res.data?.code === 1)
      isShowSuccessDialog.value = true
    else
      uni.showToast({ title: res.data?.msg, icon: 'none' })
  }
  catch (err) {
    uni.showToast({ title: JSON.stringify(err), icon: 'none' })
  }
}

/**
 * @description 退出页面
 */
function handleExit() {
  router.back()
}
</script>

<template>
  <view v-if="questionList.length > 0" class="h-screen flex flex-col bg-#0037AE px-25rpx">
    <Spacer height="52" />
    <view class="flex flex-grow-0 items-center">
      <view class="text-32rpx text-white leading-45rpx">
        答题进度
      </view>
      <Spacer width="12" />
      <view>
        <text class="text-36rpx text-white leading-50rpx">
          {{ currentIndex + 1 }}
        </text>
        <text class="text-32rpx text-white leading-50rpx">
          / {{ questionList.length }}
        </text>
      </view>
    </view>
    <Spacer height="24" />
    <ProgressBar :width="700" :progress="currentIndex / (questionList.length - 1)" />
    <Spacer height="38" />
    <view class="flex flex-grow-1 flex-col justify-between rounded-20rpx bg-white p-24rpx">
      <view>
        <view class="inline rounded-6rpx bg-#0037AE px-8rpx py-3rpx text-24rpx text-white font-semibold leading-32rpx">
          {{ questionKindName(currentQuestion.kind) }}
        </view>
        <Spacer height="24" />
        <view class="text-32rpx text-#333333 font-medium leading-45rpx">
          {{ currentQuestion.title }}
        </view>
        <Spacer height="40" />
        <block v-if="currentQuestion.kind === 'JUDGE' || currentQuestion.kind === 'SINGLE'">
          <view
            v-for="(val, key) in currentQuestion.options_json"
            :key="key"
            class="mb-12rpx flex items-center justify-between rounded-10rpx px-32rpx py-28rpx"
            :style="{
              color: currentFormData && currentFormData.answer.includes(key) ? '#0037AE' : '#333333',
              backgroundColor: currentFormData && currentFormData.answer.includes(key) ? 'rgba(0,55,174,0.1)' : '#F4F4F4',
            }"
            @tap="handleTapOption(key)"
          >
            {{ `${key}、 ${val}` }}
            <image
              v-show="currentFormData && currentFormData.answer.includes(key)"
              class="h-40rpx w-55rpx"
              src="@/static/images/checkmark_blue_l.png"
            />
          </view>
        </block>
        <textarea
          v-else
          :value="(currentFormData.answer as string)"
          class="box-border w-full rounded-10rpx bg-#F4F4F4 px-32rpx py-27rpx text-32rpx text-#333333 leading-45rpx"
          placeholder-class="text-32rpx text-#919191 leading-45rpx"
          placeholder="请输入简答内容"
          @input="handleInput"
        />
      </view>
      <view
        v-if="currentIndex === 0"
        class="mb-24rpx h-80rpx w-656rpx flex items-center justify-center rounded-full bg-#0037AE text-28rpx text-white leading-40rpx"
        hover-class="bg-#3266D9"
        @tap="handleTapNextButton"
      >
        下一题
      </view>
      <view v-if="currentIndex !== 0 && currentIndex !== questionList.length - 1" class="mb-24rpx flex items-center">
        <view
          class="h-80rpx w-320rpx flex items-center justify-center rounded-full bg-#E6E6E6 text-28rpx text-#333333 leading-40rpx"
          @tap="currentIndex > 0 ? currentIndex -= 1 : undefined"
        >
          上一题
        </view>
        <Spacer width="16" />
        <view
          class="h-80rpx w-320rpx flex items-center justify-center rounded-full bg-#0037AE text-28rpx text-white leading-40rpx"
          hover-class="bg-#3266D9"
          @tap="handleTapNextButton"
        >
          下一题
        </view>
      </view>
      <view v-if="currentIndex === questionList.length - 1" class="mb-24rpx flex items-center">
        <view
          class="h-80rpx w-320rpx flex items-center justify-center rounded-full bg-#E6E6E6 text-28rpx text-#333333 leading-40rpx"
          @tap="currentIndex > 0 ? currentIndex -= 1 : undefined"
        >
          上一题
        </view>
        <Spacer width="16" />
        <view
          class="h-80rpx w-320rpx flex items-center justify-center rounded-full bg-#0037AE text-28rpx text-white leading-40rpx"
          hover-class="bg-#3266D9"
          @tap="handleSubmit"
        >
          确认提交
        </view>
      </view>
    </view>
    <Spacer height="38" />
  </view>
  <view v-else class="h-screen w-screen flex items-center justify-center bg-#0037AE">
    <view class="text-white">
      无试题
    </view>
  </view>

  <uv-loading-page :loading="loading" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />

  <uv-overlay :show="isShowSuccessDialog" @tap="isShowSuccessDialog = false">
    <uv-transition mode="zoom-in" :show="isShowSuccessDialog">
      <view class="relative h-screen w-screen">
        <view class="absolute left-50% top-50% -translate-50%">
          <Dialog
            :show-cancel-button="false"
            title="提交成功"
            content=""
            confirm-label="确定"
            @cancel="isShowSuccessDialog = false"
            @confirm="handleExit"
          />
        </view>
      </view>
    </uv-transition>
  </uv-overlay>
</template>

<route lang="yaml">
name: 'assessment'
style:
  navigationBarTitleText: '综合评估'
  navigationBarBackgroundColor: '#0037AE'
  navigationBarTextStyle: 'white'
  disableScroll: true
layout: 'custom'
</route>
